package com.moose.operator.web.service.impl.poetry;

import com.moose.operator.common.PageInfo;
import com.moose.operator.common.QueryWrapper;
import com.moose.operator.model.entity.PoetryAuthorInfo;
import com.moose.operator.model.param.SearchParam;
import com.moose.operator.web.service.PoetryAuthorInfoService;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.bson.Document;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.stereotype.Service;

/**
 * <p>
 * Description:
 * </p>
 *
 * @author taohua
 * @version v1.0.0
 * @date 2020-12-13 22:06:22:06
 * @see com.moose.operator.web.service.impl
 */
@Service
public class PoetryAuthorInfoServiceImpl implements PoetryAuthorInfoService {
  @Resource
  private MongoTemplate mongoTemplate;

  @Override
  public PageInfo<PoetryAuthorInfo> listPoetryAuthorInfo(SearchParam searchParam) {
    Integer pageNum = searchParam.getPageNum();
    Integer pageSize = searchParam.getPageSize();
    Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.project("id", "author", "intro", "dynasty", "dynasty_id", "num"),
        Aggregation.sort(Sort.Direction.DESC, "num"),
        QueryWrapper.buildSkipOperation(pageNum, pageSize),
        QueryWrapper.buildLimitOperation(pageSize));

    AggregationResults<Document> aggregate =
        mongoTemplate.aggregate(aggregation, "poetry_author_info", Document.class);

    List<Document> mappedResults = aggregate.getMappedResults();

    List<PoetryAuthorInfo> authorInfoList = mappedResults.stream().map(document -> {
      PoetryAuthorInfo poetryAuthorInfo = new PoetryAuthorInfo();
      poetryAuthorInfo.setId(document.getInteger("id"));
      poetryAuthorInfo.setAuthorName(document.getString("author"));
      poetryAuthorInfo.setIntro(document.getString("intro"));
      poetryAuthorInfo.setDynasty(document.getString("dynasty"));
      poetryAuthorInfo.setDynastyId(document.getInteger("dynasty_id"));
      Integer collected = document.getInteger("num");
      poetryAuthorInfo.setCollected(null == collected ? 0 : collected);
      return poetryAuthorInfo;
    }).collect(Collectors.toList());

    long totalSize = mongoTemplate.count(QueryWrapper.buildQuery(), PoetryAuthorInfo.class);
    PageInfo<PoetryAuthorInfo> pageInfo = new PageInfo<>();
    pageInfo.setList(authorInfoList);
    pageInfo.setPageSize(pageSize);
    pageInfo.setTotalSize(totalSize);
    pageInfo.setPageNum(pageNum);
    return pageInfo;
  }
}
